<?php

namespace app\admin\controller;

use DateTime;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Queue;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    public function test()
    {
        return $this->view->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }


    /**
     * 用户列表
     * */
    public function userList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'] ? : '';
        $company_name = $input['company_name'] ? : '';
        $user_type = $input['user_type'] ? : 0;
        $status = $input['status'] ? : 0;
        $date_range = $input['date_range'] ? : '';
        $up_channel_user_id = $input['up_channel_user_id'] ? : 0;
        $up_salesman_user_id = $input['up_salesman_user_id'] ? : 0;

        $where['is_admin'] = 0;

        if ($mobile) $where['mobile'] = $mobile;
        if ($company_name) $where['supplier_company_name|channel_company_name'] = ['like', "%$company_name%"];
        switch ($user_type) {
            case 1:
                $where['supplier_id'] = ['gt', 0];
                if ($status) $where['supplier_status'] = $status;
                break;
            case 2:
                $where['channel_id'] = ['gt', 0];
                if ($status) $where['channel_status'] = $status;
                break;
            case 3:
                $where['salesman_id'] = ['gt', 0];
                if ($status) $where['salesman_status'] = $status;
                break;
            default:
                if ($status) $where['supplier_status|channel_status|salesman_status'] = $status;
                break;
        }
        if ($date_range) {
            $date = explode(' - ', $date_range);
            $start_time = strtotime($date[0]);
            $end_time = strtotime($date[1]);

            $where["create_time"] = ['between', [$start_time, $end_time + 60 * 60 * 24 - 1]];
        }

        if ($up_channel_user_id) $where['up_channel_user_id'] = $up_channel_user_id;
        if ($up_salesman_user_id) $where['up_salesman_user_id'] = $up_salesman_user_id;

        $list = Db::name('user')->where($where)->order('id desc')->paginate()->each(function ($v) {
            if ($v['supplier_id'] || $v['channel_id'] || $v['salesman_id']) {
                $ids = [$v['supplier_id'], $v['channel_id'], $v['salesman_id']];
                $ids = array_values(array_filter($ids));
                $user_ident_list = Db::name('user_ident')->field('id,company_name,yyzz_img,username,mobile,status')->where(['id' => ['IN', $ids]])->select();

                $ident_list = [];
                if ($user_ident_list) {
                    foreach ($user_ident_list as $val) {
                        switch ($val['id']) {
                            case $v['supplier_id']:
                                $ident_list['supplier_info'] = $val;
                                break;
                            case $v['channel_id']:
                                $ident_list['channel_info'] = $val;
                                break;
                            case $v['salesman_id']:
                                $ident_list['salesman_info'] = $val;
                                break;
                        }
                    }
                }
                $v['ident_list'] = $ident_list;

                $company_name = $v['supplier_company_name'] ? : '';
                $v['company_name'] .= $v['channel_company_name'] ? "<br />" . $v['channel_company_name'] : $company_name;
            }

            if ($channel_type_ids = $v['channel_type_ids']) {
                $channel_type = Db::name('service_type')->where(['id' => ['IN', $channel_type_ids]])->column('name');
                $v['channel_type_name'] = implode("<br />", $channel_type);
            }

            return $v;
        });

        $this->assign('list', $list);

        $service_type_list = Db::name('service_type')->order('id asc')->select();
        $this->assign('service_type_list', json_encode($service_type_list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '用户列表');

        return $this->view->fetch();
    }

    /**
     * 一键重置小程序码
     * */
    public function resetQr()
    {
        Db::startTrans();
        try {
            $res = Db::name('user')->where(['is_admin' => 0])->update(['channel_qr' => '', 'salesman_qr' => '']);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }

            $list = Db::name('user')->where(['is_admin' => 0])->column('id');
            foreach ($list as $v) {
                createChannelQr($v);
                createSalesmanQr($v);
            }

            Db::commit();
            adminReturn(1, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败' . $e->getMessage());
        }
    }

    /**
     * 认证审核
     * */
    public function identConfirmStatus()
    {
        $input = Request()->param();

        $id = $input['id'];
        $status = $input['status'] ? : 0;
        $remark = $input['remark'] ? : '';

        if (empty($id)) adminReturn(2, '参数错误');

        $user_ident = Db::name('user_ident')->where(['id' => $id])->find();
        if (empty($user_ident)) adminReturn(2, '认证信息不存在');

        Db::startTrans();
        try {
            $res = Db::name('user_ident')->where(['id' => $id])->update(['status' => $status, 'remark' => $remark, 'update_time' => time()]);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }

            $user_id = $user_ident['user_id'];

            $user_status = '';
            switch ($user_ident['type']) {
                case 1:
                    $user_status = 'supplier_status';
                    break;
                case 2:
                    $user_status = 'channel_status';
                    break;
                case 3:
                    $user_status = 'salesman_status';
                    break;
            }

            if ($status == 1) {
                // 认证审核通过
                if ($user_ident['type'] == 1) {
                    Db::name('user')->where(['id' => $user_id])->setField('supplier_company_name', $user_ident['company_name']);

                    $up_salesman_user_id = Db::name('user')->field('up_salesman_user_id,son_supplier_count')->where(['id' => $user_id])->value('up_salesman_user_id');
                    if ($up_salesman_user_id) {
                        // 找到上级业务员，发展供应商人数+1，评分增加
                        $res = Db::name('user')->where(['id' => $up_salesman_user_id])->setInc('son_supplier_count');
                        if (!$res) {
                            Db::rollback();
                            adminReturn(2, '操作失败');
                        }

                        $salesman_share_score = C('SALESMAN_SHARE_SCORE');
                        if ($salesman_share_score > 0) {
                            // 生成上级业务员评分记录
                            $up_salesman_ident_id = Db::name('user')->where(['id' => $up_salesman_user_id])->value('salesman_id');
                            $res = doScore($up_salesman_user_id, $up_salesman_ident_id, 'salesman_score', $salesman_share_score, 'share_register', $user_id, 'pu_user', '业务员拉新奖励');
                            if (!$res) {
                                Db::rollback();
                                adminReturn(2, '操作失败');
                            }
                        }
                    }
                } elseif ($user_ident['type'] == 3) {
                    // 生成业务员推广二维码
                    createSalesmanQr($user_id);

                    // 找到上级渠道商，发展业务员人数+1
                    $up_channel_user_id = Db::name('user')->where(['id' => $user_id])->value('up_channel_user_id');
                    if ($up_channel_user_id) {
                        $res = Db::name('user')->where(['id' => $up_channel_user_id])->setInc('son_salesman_count');
                        if (!$res) {
                            Db::rollback();
                            adminReturn(2, '操作失败');
                        }
                    }

                } elseif ($user_ident['type'] == 2) {
                    Db::name('user')->where(['id' => $user_id])->setField('channel_company_name', $user_ident['company_name']);

                    // 生成渠道商推广二维码
                    createChannelQr($user_id);
                }
            }

            Db::name('user')->where(['id' => $user_id])->setField($user_status, $status + 1);

            Db::commit();
            adminReturn(1, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 修改渠道商服务类目
     * */
    public function saveChannelTypeIds()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $channel_type_ids = $input['channel_type_ids'];

        if (empty($user_id)) adminReturn(2, '参数错误');

        $res = Db::name('user')->where(['id' => $user_id])->update(['channel_type_ids' => $channel_type_ids, 'update_time' => time()]);
        if ($res) {
            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 渠道商异常处罚
     * */
    public function punishChannel()
    {
        $input = Request()->param();

        $id = $input['id'];
        $type = $input['type'];
        $score = $input['score'] ? : 0;
        $day = $input['day'] ? ($input['day'] + 1) : 0;

        if (empty($id)) adminReturn(2, '参数错误');
        if ($type == 1 && $score <= 0) adminReturn(2, '请输入扣除评分数值');
        if ($type == 2 && $day == 0) adminReturn(2, '请输入禁止接单天数');

        $user_info = Db::name('user')->where(['id' => $id])->find();
        if (empty($user_info)) adminReturn(2, '用户不存在');

        Db::startTrans();
        try {
            if ($type == 1) {
                // 处罚扣评分
                $res = doScore($id, $user_info['channel_id'], 'channel_score', 0 - $score, 'admin_punish', $id, 'pu_user', '渠道商异常处罚，扣除 ' . $score . ' 积分');
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                // 针对异常的渠道商，处罚扣评分完成后就自动解除异常了
                $user_data = [
                    'channel_reset_time' => time(),
                    'channel_is_normal' => 1,
                    'channel_is_send_order' => 1
                ];
                $res = Db::name('user')->where(['id' => $id])->update($user_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }
            } else {
                // 处罚禁止接单
                $date = new DateTime(date('Y-m-d'));
                $date->modify("+{$day} days");
                // 自动解除处罚时间
                $channel_reset_time = strtotime($date->format('Y-m-d'));
                $user_data = [
                    'channel_reset_time' => $channel_reset_time,
                    'channel_is_normal' => 0,
                    'channel_is_send_order' => 0
                ];
                $res = Db::name('user')->where(['id' => $id])->update($user_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }
            }

            Db::commit();
            adminReturn(1, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败');
        }

    }

    /**
     * 操作用户积分
     * */
    public function setUserIntegral()
    {
        $input = Request()->param();

        $id = $input['id'];
        $integral = $input['integral'];
        $remark = $input['remark'];

        if (empty($id)) adminReturn(2, '参数错误');
        if ($integral == 0) adminReturn(2, '请输入积分');
        if (!$remark) adminReturn(2, '请输入备注');

        $user_info = Db::name('user')->where(['id' => $id])->find();
        if (empty($user_info)) adminReturn(2, '用户不存在');

        Db::startTrans();
        try {
            $log_data = [
                'user_id' => $id,
                'integral' => $integral,
                'before' => $user_info['integral'],
                'type' => 'admin_post',
                'remark' => $remark,
                'create_time' => time(),
                'link_id' => $id,
                'link_table' => 'pu_user'
            ];

            if ($integral > 0) {
                $log_data['after'] = $user_info['integral'] + abs($integral);
                $res = Db::name('user_integral_log')->insert($log_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                $res = Db::name('user')->where(['id' => $id])->setInc('integral', abs($integral));
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }
            } else {
                $after = $user_info['integral'] - abs($integral);
                if ($after < 0) {
                    Db::rollback();
                    adminReturn(2, '积分不足');
                }
                $log_data['after'] = $after;
                $res = Db::name('user_integral_log')->insert($log_data);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }

                $res = Db::name('user')->where(['id' => $id])->setDec('integral', abs($integral));
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }
            }

            Db::commit();
            adminReturn(1, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 认证关系转移
     * */
    public function identUserMove()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $type = $input['type'];
            $channel_ident_id = $input['channel_ident_id'] ? : 0;
            $supplier_ident_id = $input['supplier_ident_id'] ? : 0;
            $user_id = $input['user_id'];

            if ($type == 1 && $supplier_ident_id == 0) adminReturn(2, '请选择供应商');
            if ($type == 2 && $channel_ident_id == 0) adminReturn(2, '请选择渠道商');
            if (empty($user_id)) adminReturn(2, '请选择用户');

            $user_info = Db::name('user')->where(['id' => $user_id])->find();
            if (empty($user_info)) adminReturn(2, '用户不存在');

            Db::startTrans();
            try {
                if ($type == 1) {
                    // 供应商
                    if ($user_info['supplier_id'] > 0) adminReturn(2, '该用户已是供应商，操作失败');


                    $ident_info = Db::name('user_ident')->where(['id' => $supplier_ident_id])->find();
                    $old_user_id = $ident_info['user_id'];

                    if ($old_user_id == $user_id) adminReturn(2, '供应商和用户为同一个用户数据，操作失败');

                    $res = Db::name('user_ident')->where(['id' => $supplier_ident_id])->setField('user_id', $user_id);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '操作失败');
                    }

                    // 修改被转移的用户数据
                    $res = Db::name('user')->where(['id' => $old_user_id])->setField('supplier_id', 0);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '操作失败');
                    }

                    // 修改新用户的数据
                    $res = Db::name('user')->where(['id' => $user_id])->setField('supplier_id', $supplier_ident_id);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '操作失败');
                    }
                } else {
                    // 渠道商
                    if ($user_info['channel_id'] > 0) adminReturn(2, '该用户已是渠道商，操作失败');

                    $ident_info = Db::name('user_ident')->where(['id' => $channel_ident_id])->find();
                    $old_user_id = $ident_info['user_id'];
                    if ($old_user_id == $user_id) adminReturn(2, '渠道商和用户为同一个用户数据，操作失败');
                    if ($user_info['up_channel_user_id'] == $old_user_id) adminReturn(2, '该用户是该渠道商的下级，操作失败');

                    $res = Db::name('user_ident')->where(['id' => $channel_ident_id])->setField('user_id', $user_id);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '操作失败');
                    }

                    $old_user_info = Db::name('user')->where(['id' => $old_user_id])->find();

                    // 修改被转移的用户数据
                    $old_user_data = [
                        'channel_id' => 0,
                        'channel_qr' => '',
                        'channel_score' => 0,
                        'channel_type_ids' => '',
                    ];
                    $res = Db::name('user')->where(['id' => $old_user_id])->update($old_user_data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '操作失败');
                    }

                    // 修改新用户的数据
                    $new_user_data = [
                        'channel_id' => $channel_ident_id,
                        'channel_score' => $old_user_info['channel_score'],
                        'channel_type_ids' => $old_user_info['channel_type_ids'],
                    ];
                    $res = Db::name('user')->where(['id' => $user_id])->update($new_user_data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '操作失败');
                    }

                    // 生成渠道商推广码
                    createChannelQr($user_id);

                    // 修改原渠道商下级用户的关系转移
                    $res = Db::name('user')->where(['up_channel_user_id' => $old_user_id])->setField('up_channel_user_id', $user_id);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '操作失败');
                    }
                }

                Db::commit();
                adminReturn(1, '操作成功', url('identUserMove'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }


        } else {
            // 渠道商认证列表
            $channel_ident_list = Db::name('user_ident')->where(['type' => 2])->order('id desc')->select();
            $this->assign('channel_ident_list', $channel_ident_list);

            // 供应商认证列表
            $supplier_ident_list = Db::name('user_ident')->where(['type' => 1])->order('id desc')->select();
            $this->assign('supplier_ident_list', $supplier_ident_list);

            // 用户列表
            $user_list = Db::name('user')->where(['is_admin' => 0])->order('id desc')->select();
            $this->assign('user_list', $user_list);

            $this->assign('title', '认证关系转移');

            return $this->view->fetch();
        }
    }

    /**
     * 积分列表
     * */
    public function integralList()
    {
        $input = Request()->param();

        $type = $input['type'] ? : '';
        $user_id = $input['user_id'] ? : 0;

        if ($type) $where['l.type'] = $type;
        if ($user_id) $where['l.user_id'] = $user_id;

        $list = Db::name('user_integral_log l')->join('user u', 'l.user_id = u.id', 'left')
            ->field('l.*,u.username,u.mobile')
            ->where($where)
            ->paginate();
        $this->assign('list', $list);

        $this->assign('title', '积分列表');

        return $this->view->fetch();
    }

    /**
     * 服务列表
     * */
    public function serviceList()
    {
        $input = Request()->param();

        $type_id = $input['type_id'] ? : 0;

        if ($type_id) $where['type_id'] = $type_id;

        $list = Db::name('service')->where($where)->order('sort asc')->paginate()->each(function ($val) {
            $type_name = Db::name('service_type')->where(['id' => $val['type_id']])->value('name');
            $val['type_name'] = $type_name ? : '';
            return $val;
        });
        $this->assign('list', $list);

        $this->assign('title', '服务列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 服务
     * */
    public function doService()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $name = $input['name'];
            $desc = $input['desc'];
            $type_id = $input['type_id'];
            $virtual_count = $input['virtual_count'];
            $is_hot = $input['is_hot'];
            $sort = $input['sort'];
            $content = $input['content'];
            $know = $input['know'];
            $status = $input['status'];

            if (empty($name)) adminReturn(2, '请输入名称');
            if (empty($type_id)) adminReturn(2, '请选择类目');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('service')->where($where)->count();
            if ($count > 0) adminReturn(2, '该名称已存在');

            $data = [
                'name' => $name,
                'desc' => $desc,
                'type_id' => $type_id,
                'virtual_count' => $virtual_count,
                'is_hot' => $is_hot,
                'sort' => $sort,
                'content' => $content,
                'know' => $know,
                'status' => $status,
            ];

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('service')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('serviceList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data['create_time'] = time();
                $res = Db::name('service')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('serviceList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('service')->where(['id' => $id])->find();
            }

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '服务');

            $service_type_list = Db::name('service_type')->select();
            $this->assign('service_type_list', $service_type_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除服务
     * */
    public function delService()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '服务ID缺失');

        $info = Db::name('service')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('service')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }


    /**
     * 类目列表
     * */
    public function serviceTypeList()
    {
        $list = Db::name('service_type')->order('sort asc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '类目列表');
        return $this->view->fetch();
    }


    /**
     * 快捷入口排序
     * */
    public function sortServiceType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('service_type')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 新增/编辑 类目
     * */
    public function doServiceType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('service_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该名称已存在');

            $data = [
                'name' => $name
            ];

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('service_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑类目成功', url('serviceTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data['create_time'] = time();
                $res = Db::name('service_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增类目成功', url('serviceTypeList'));
                } else {
                    adminReturn(2, '新增类目失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('service_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '类目');

            return $this->view->fetch();
        }
    }


    /**
     * 删除类目
     * */
    public function delServiceType()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '类目ID缺失');

        $info = Db::name('service_type')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('service_type')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }


    /**
     * 文章列表
     * */
    public function articleList()
    {
        $input = Request()->param();

        $title = $input['title'];

        if ($title) $where['title'] = ['like', '%' . $title . '%'];

        $page_list = Db::name('article')->where($where)->order('sort asc')->paginate();

        $this->assign('page_list', $page_list);
        $this->assign('title', '文章列表');

        $list = Db::name('article')->order('sort asc')->select();
        $this->assign('list', $list);

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $content = $input['content'];

            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'title' => $title,
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 文章排序
     * */
    public function sortArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('article')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 运费模板
     * */
    public function freightList()
    {
        $list = Db::name('freight')->paginate();


        $this->assign('list', $list);
        $this->assign('title', '运费模板');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 运费模板
     * */
    public function doFreight()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $type = $input['type'];
            $init_count = $input['init_count'];
            $init_count_price = $input['init_count_price'];
            $inc_count = $input['inc_count'];
            $inc_count_price = $input['inc_count_price'];
            $init_weight = $input['init_weight'];
            $init_weight_price = $input['init_weight_price'];
            $inc_weight = $input['inc_weight'];
            $inc_weight_price = $input['inc_weight_price'];
            $diff_freight = $input['diff_freight'];

            if (empty($name)) apiReturn(2, '请输入模板名称');

            $where['name'] = $name;
            if ($id > 0) $where['id'] = ['neq', $id];
            $count = Db::name('freight')->where($where)->count();
            if ($count > 0) adminReturn(2, '模板名称已存在');


            if (($type == 1 && (empty($init_count) || empty($init_count_price) || empty($inc_count) || empty($inc_count_price)))
                ||
                ($type == 2 && (empty($init_weight) || empty($init_weight_price) || empty($inc_weight) || empty($inc_weight_price)))
            ) adminReturn(2, '请完善计价规格');

            $time = time();
            $data = [
                'name' => $name,
                'type' => $type,
                'init_count' => $init_count,
                'init_count_price' => $init_count_price,
                'inc_count' => $inc_count,
                'inc_count_price' => $inc_count_price,
                'init_weight' => $init_weight,
                'init_weight_price' => $init_weight_price,
                'inc_weight' => $inc_weight,
                'inc_weight_price' => $inc_weight_price,
                'diff_freight' => $diff_freight,
            ];

            if ($id > 0) {
                // 编辑
                $data['update_time'] = $time;
                $res = Db::name('freight')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('freightList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                // 新增
                $data['create_time'] = $time;
                $res = Db::name('freight')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('freightList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('freight')->where(['id' => $id])->find();

            $province_list = Db::name('province')->field('province_id,name province_name')->select();
            if ($province_list) {
                foreach ($province_list as &$v) {
                    $city_list = Db::name('city')->field('city_id,name city_name')->where(['province_id' => $v['province_id']])->select();
                    $v['city_list'] = $city_list;
                }
            }

            $info['diff_freight_list'] = json_decode($info['diff_freight'], true);
            $this->assign('diff_freight_data', $info['diff_freight'] ? $info['diff_freight'] : json_encode([]));
            $this->assign('info', $info);
            $this->assign('province_list', $province_list);
            $this->assign('title', ($id ? '编辑' : '新增') . '运费模板');
            return $this->view->fetch();
        }
    }

    /**
     * 服务保障
     * */
    public function serviceGuarantee()
    {
        if (Request()->isPost()) {
            $service_guarantee = Request()->param('service_guarantee');

            $res = Db::name('goods_service_guarantee')->where(' 1 = 1 ')->setField(['service_guarantee' => $service_guarantee]);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $service_guarantee = Db::name('goods_service_guarantee')->value('service_guarantee');

            $this->assign('service_guarantee', json_decode($service_guarantee, true));
            $this->assign('title', '服务保障');
            return $this->view->fetch();
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $one_type_id = $input['one_type_id'];
        $two_type_id = $input['two_type_id'];

        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($two_type_id) $where['two_type_id'] = $two_type_id;

        $list = Db::name('goods')->where($where)->order('create_time desc')->paginate()->each(function ($item) {
            $item['one_type_name'] = Db::name('goods_type')->where(['id' => $item['one_type_id']])->value('name');
            $item['two_type_name'] = Db::name('goods_type')->where(['id' => $item['two_type_id']])->value('name');

            return $item;
        });

        $type_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => 0])->select();
        if ($type_list) {
            foreach ($type_list as &$v) {
                $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                $v['son_list'] = $son_list;
            }
        }
        $this->assign('list', $list);

        $this->assign('type_list', $type_list);
        $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '商品列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 商品
     * */
    public function doGoods()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            Db::startTrans();
            try {
                //参数处理
                parse_str($input['form'], $form);

                $price_arr = [];
                if ($form['skus']) {
                    foreach ($form['skus'] as $v) {
                        if ($v['status'] == 1) $price_arr[] = $v['price'];
                    }
                }

                $min_price = min($price_arr);
                $max_price = max($price_arr);

                $skus = $form['skus'];
                unset($form['skus']);

                $id = $form['id'];

                if (empty($form['name'])) adminReturn(2, '请输入商品名称');
                if (empty($form['img'])) adminReturn(2, '请上传封面图');
                if (empty($form['content'])) adminReturn(2, '请输入商品介绍');
                $time = time();

                $data = [
                    'name' => $form['name'],
                    'img' => $form['img'],
                    'imgs' => $form['imgs'],
                    'one_type_id' => $form['one_type_id'],
                    'two_type_id' => $form['two_type_id'],
                    'skus' => $input['skus'],
                    'min_price' => $min_price >= 0 ? $min_price : 0,
                    'max_price' => $max_price >= 0 ? $max_price : 0,
                    'product_param' => $form['product_param'] ? $form['product_param'] : '',
                    'user_instructions' => $form['user_instructions'],
                    'content' => $form['content']
                ];

                if ($id > 0) {
                    $activity_count = Db::name('activity_log')->where(['goods_id' => $id])->count();
                    if ($activity_count) adminReturn(2, '该商品活动未结束，无法编辑');

                    //编辑
                    $data['update_time'] = $time;

                    Db::name('goods')->where(['id' => $id])->update($data);

                    Db::name('sku_value')->where(['goods_id' => $id])->delete();

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    //此行请勿删除
                    cache('sku_' . $id, null);

                    Db::commit();
                    adminReturn(1, '编辑商品成功', url('goodsList'));
                } else {
                    //新增
                    $data['create_time'] = $time;

                    $goods_id = Db::name('goods')->insertGetId($data);

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $goods_id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    Db::commit();
                    adminReturn(1, '新增商品成功', url('goodsList'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~' . $e);
            }
        } else {
            $id = Request()->param('id');

            $info = Db::name('goods')->where(['id' => $id])->find();
            $info['imgs_arr'] = doImgs($info['imgs']);
            $info['product_param'] = json_decode($info['product_param'], true);

            $type_list = Db::name('goods_type')->field('id,name')->where(['pid' => 0])->select();
            if ($type_list) {
                foreach ($type_list as &$v) {
                    $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                    $v['son_list'] = $son_list;
                }
            } else {
                $type_list = [];
            }

            $sku_list = Db::name('sku')->field('id,name title')->where(['pid' => 0])->cache('sku')->select();
            if ($sku_list) {
                //$skus_id_arr：所有属性的id集合
                $skus_id_arr = [];

                foreach ($sku_list as &$v) {
                    if ($id > 0) {
                        $sku_value_list = Db::name('sku_value')->field('sku_id')->where(['goods_id' => $id])->select();

                        if ($sku_value_list) {
                            foreach ($sku_value_list as &$val) {
                                $sku_id = explode(' - ', $val['sku_id']);
                                if ($sku_id) {
                                    foreach ($sku_id as &$value) {
                                        if (!in_array($value, $skus_id_arr)) {
                                            $skus_id_arr[] = $value;
                                        }
                                    }
                                }
                            }
                        }

                        $parent_list = Db::name('sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr]])->select();
                        $parent_ids = array_column($parent_list, 'pid');

                        $v['checked'] = false;
                        if (in_array($v['id'], $parent_ids)) $v['checked'] = true;
                    } else {
                        $v['checked'] = false;
                    }

                    $child = Db::name('sku')->field('id,name title')->where(['pid' => $v['id']])->select();
                    if ($child) {
                        foreach ($child as &$val) {
                            $val['checked'] = in_array($val['id'], $skus_id_arr) ? true : false;
                        }
                    }
                    $v['child'] = $child;
                }
            }

            $this->assign('title', $id ? '编辑商品' : '新增商品');

            $this->assign('info', $info);
            $this->assign('type_list', $type_list);
            $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));
            $this->assign('sku_list', json_encode($sku_list, JSON_UNESCAPED_UNICODE));
            return $this->fetch();
        }
    }

    /**
     * 删除商品
     * */
    public function delGoods()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '商品ID缺失');

        $info = Db::name('goods')->where(['id' => $id])->find();
        if ($info) {
            $activity_count = Db::name('activity_log')->where(['goods_id' => $id])->count();
            if ($activity_count) adminReturn(2, '该商品活动未结束，无法删除');

            $res = Db::name('goods')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 团购活动
     * */
    public function groupList()
    {
        $list = Db::name('group')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '团购活动');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 团购
     * */
    public function doGroup()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $goods_id = $input["goods_id"];
            $start_time = strtotime($input["start_time"]);
            $end_time = strtotime($input["end_time"]) + 24 * 3600 - 1;
            $people_number = $input["people_number"];
            $time_limit = $input["time_limit"];
            $group_price = $input["group_price"];
            $chief_price = $input["chief_price"];
            $group_limit_number = $input["group_limit_number"];

            $time = time();

            if (empty($goods_id)) apiReturn(2, '请选择商品');
            if (empty($start_time) && empty($end_time)) adminReturn(2, "请选择拼团时间");
            if ($end_time <= $time || $end_time <= $start_time) adminReturn(2, '结束拼团时间有误，请重新设置');
            if (empty($people_number)) adminReturn(2, "请输入拼团人数");
            if (empty($time_limit)) adminReturn(2, "请输入拼团时限");
            if (empty($group_price)) adminReturn(2, "请输入成团价格");
            if (empty($chief_price)) adminReturn(2, "请输入团长价格");
            if (empty($group_limit_number)) adminReturn(2, "请输入限制成团数");

            Db::startTrans();
            try {
                $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                if (empty($goods_info)) adminReturn(2, '商品不存在或已删除');

                $data = [
                    'one_type_id' => $goods_info['one_type_id'],
                    'two_type_id' => $goods_info['two_type_id'],
                    'brand_id' => $goods_info['brand_id'],
                    'goods_name' => $goods_info['name'],
                    'goods_id' => $goods_id,
                    "start_time" => $start_time,
                    "end_time" => $end_time,
                    "people_number" => $people_number,
                    "time_limit" => $time_limit,
                    "group_price" => $group_price,
                    "chief_price" => $chief_price,
                    "group_limit_number" => $group_limit_number,
                ];

                if ($id > 0) {
                    $data['update_time'] = $time;
                    Db::name('group')->where(['id' => $id])->update($data);
                } else {
                    $data['create_time'] = $time;
                    $group_id = Db::name('group')->insertGetId($data);

                    Db::name('activity_log')->insert(['goods_id' => $goods_id, 'type' => 1]);

                    if ($group_id) {
                        $job_name = 'app\index\job\JobOrder';
                        $queue_name = "JobActivity";
                        $job_data = [
                            'obj_id' => $group_id,
                            'type' => 'group',
                        ];

                        if ($start_time > $time) {
                            // 未开始

                            // 新增开始团购活动任务
                            $job_data['node'] = 'start';
                            $start_task = Queue::later($start_time - $time, $job_name, $job_data, $queue_name);
                            if (!($start_task !== false)) {
                                Db::rollback();
                                adminReturn(2, '团购开始任务新增失败');
                            }
                        }

                        // 新增结束团购活动任务
                        $job_data['node'] = 'end';
                        $end_task = Queue::later($end_time - $time, $job_name, $job_data, $queue_name);
                        if (!($end_task !== false)) {
                            Db::rollback();
                            adminReturn(2, '团购结束任务新增失败');
                        }
                        Db::commit();
                        adminReturn(1, '提交成功', url('groupList'));
                    } else {
                        adminReturn(2, '提交失败');
                    }
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('group')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '团购');

            $activity_log = Db::name('activity_log')->field('goods_id')->select();
            $activity_goods_ids = array_column($activity_log, 'goods_id');
            if ($activity_goods_ids) $where['id'] = ['NOT IN', $activity_goods_ids];

            $goods_list = Db::name('goods')->field('id,name')->where(['activity_type' => 0, 'upper' => 1])->where($where)->select();
            $this->assign('goods_list', $goods_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除团购
     * */
    public function delGroup()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '团购ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('group')->where(['id' => $id])->find();

            if ($info) {
                Db::name('group')->where(['id' => $id])->delete();

                Db::name('goods')->where(['id' => $info['goods_id']])->setField('activity_type', 0);

                Db::name('activity_log')->where(['goods_id' => $info['goods_id']])->delete();

                $start_job_payload = [
                    'job' => 'app\index\job\JobOrder',
                    'data' => [
                        'obj_id' => $id,
                        'type' => 'group',
                        'node' => 'start'
                    ]
                ];
                $have_start_job = Db::name('jobs')->where(['payload' => json_encode($start_job_payload, JSON_UNESCAPED_UNICODE)])->count();
                if ($have_start_job) Db::name('jobs')->where(['payload' => json_encode($start_job_payload, JSON_UNESCAPED_UNICODE)])->delete();

                $end_job_payload = [
                    'job' => 'app\index\job\JobOrder',
                    'data' => [
                        'obj_id' => $id,
                        'type' => 'group',
                        'node' => 'end'
                    ]
                ];
                $have_end_job = Db::name('jobs')->where(['payload' => json_encode($end_job_payload, JSON_UNESCAPED_UNICODE)])->count();
                if ($have_end_job) Db::name('jobs')->where(['payload' => json_encode($end_job_payload, JSON_UNESCAPED_UNICODE)])->delete();

                Db::commit();
                adminReturn(1, '删除成功');
            } else {
                Db::rollback();
                adminReturn(2, '团购活动不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 秒杀活动
     * */
    public function seckillList()
    {
        $list = Db::name('seckill')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '秒杀活动');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 秒杀
     * */
    public function doSeckill()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $goods_id = $input["goods_id"];
            $start_time = strtotime($input["start_time"]);
            $end_time = strtotime($input["end_time"]);
            $price = $input["price"];
            $count = $input["count"];

            $time = time();

            if (empty($goods_id)) apiReturn(2, '请选择商品');
            if (empty($start_time) && empty($end_time)) adminReturn(2, "请选择拼团时间");
            if ($end_time <= $time || $end_time <= $start_time) adminReturn(2, '结束拼团时间有误，请重新设置');
            if (empty($goods_id)) adminReturn(2, "请选择秒杀商品");
            if (empty($price)) apiReturn(2, '请输入秒杀价格');
            if (empty($count)) apiReturn(2, '请输入秒杀数量');

            Db::startTrans();
            try {
                $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                if (empty($goods_info)) adminReturn(2, '商品不存在或已删除');

                $data = [
                    'one_type_id' => $goods_info['one_type_id'],
                    'two_type_id' => $goods_info['two_type_id'],
                    'brand_id' => $goods_info['brand_id'],
                    'goods_name' => $goods_info['name'],
                    "goods_id" => $goods_id,
                    "start_time" => $start_time,
                    "end_time" => $end_time,
                    "price" => $price,
                    "count" => $count,
                    "surplus_count" => $count
                ];

                if ($start_time >= $time) {
                    // 活动中

                    $data['status'] = 1;

                    Db::name('goods')->where(['goods_id' => $goods_id])->setField('activity_type', 2);
                } else {
                    // 未开始

                }

                if ($id > 0) {
                    $data['update_time'] = $time;
                    Db::name('seckill')->where(['id' => $id])->update($data);
                } else {
                    $data['create_time'] = $time;
                    Db::name('seckill')->insert($data);

                    Db::name('activity_log')->insert(['goods_id' => $goods_id, 'type' => 2]);
                }

                Db::commit();
                adminReturn(1, '提交成功', url('seckillList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('seckill')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '秒杀');

            $activity_log = Db::name('activity_log')->field('goods_id')->select();
            $activity_goods_ids = array_column($activity_log, 'goods_id');

            if ($activity_goods_ids) $where['id'] = ['NOT IN', $activity_goods_ids];

            $goods_list = Db::name('goods')->field('id,name')->where(['activity_type' => 0, 'upper' => 1])->where($where)->select();
            $this->assign('goods_list', $goods_list);


            return $this->view->fetch();
        }
    }

    /**
     * 删除秒杀活动
     * */
    public function delSeckill()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '秒杀活动ID缺失');

        $info = Db::name('seckill')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('seckill')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('banner')->order('sort asc')->paginate()->each(function ($val) {
            if ($val['type'] == 1) {
                $name = Db::name('service')->where(['id' => $val['to_id']])->value('name');
                $val['obj_name'] = $name ? : '';
            } else {
                $title = Db::name('article')->where(['id' => $val['to_id']])->value('title');
                $val['obj_name'] = $title ? : '';
            }

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }


    /**
     * banner排序
     * */
    public function sortBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('banner')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $position = $input['position'] ? : 1;
            $type = $input["type"] ? : 0;
            $to_id = $input["to_id"] ? : 0;

            if (empty($img)) adminReturn(2, '请上传banner图');

            $data = [
                "img" => $img,
                "position" => $position,
                "type" => $type,
                'to_id' => $to_id
            ];

            if ($id > 0) {
                $res = Db::name('banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $res = Db::name('banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('banner')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            $service_list = Db::name('service_type')->field('id,name')->select();
            if ($service_list) {
                foreach ($service_list as &$v) {
                    $service = Db::name('service')->field('id,name')->where(['type_id' => $v['id']])->order('sort asc')->select();
                    $v['service'] = $service ? : [];
                }
            }
            $this->assign('service_list', $service_list);
            $this->assign('service_list_obj', json_encode($service_list, JSON_UNESCAPED_UNICODE));

            $article_list = Db::name('article')->field('id,title')->select();
            $this->assign('article_list', $article_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 快捷入口列表
     */
    public function serviceQuickList()
    {
        $page_list = Db::name('service_quick')->order('sort asc')->paginate()->each(function ($val) {
            $name = Db::name('service')->where(['id' => $val['service_id']])->value('name');
            $val['service_name'] = $name ? : '';

            return $val;
        });

        $this->assign('page_list', $page_list);
        $this->assign('title', '快捷入口列表');

        $list = Db::name('service_quick')->order('sort asc')->select();
        $this->assign('list', $list);

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 快捷入口列
     * */
    public function doServiceQuick()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $name = $input['name'];
            $service_id = $input["service_id"];

            if (empty($img)) adminReturn(2, '请上传封面图');
            if (empty($name)) adminReturn(2, '请输入名称');
            if (empty($service_id)) adminReturn(2, '请选择服务');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('service_quick')->where($where)->count();
            if ($count > 0) adminReturn(2, '该名称已存在');

            $data = [
                "img" => $img,
                "name" => $name,
                'service_id' => $service_id
            ];

            if ($id > 0) {
                $res = Db::name('service_quick')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑快捷入口成功', url('serviceQuickList'));
                } else {
                    adminReturn(2, '编辑快捷入口失败或未编辑');
                }
            } else {
                $res = Db::name('service_quick')->insert($data);
                if ($res) {
                    adminReturn(1, '新增快捷入口成功', url('serviceQuickList'));
                } else {
                    adminReturn(2, '新增快捷入口失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('service_quick')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '快捷入口');

            $service_list = Db::name('service_type')->field('id,name')->select();
            if ($service_list) {
                foreach ($service_list as &$v) {
                    $service = Db::name('service')->field('id,name')->where(['type_id' => $v['id']])->order('sort asc')->select();
                    $v['service'] = $service ? : [];
                }
            }
            $this->assign('service_list', $service_list);
            $this->assign('service_list_obj', json_encode($service_list, JSON_UNESCAPED_UNICODE));

            $list = Db::name('service_quick')->order('sort asc')->select();
            $this->assign('list', $list);

            return $this->view->fetch();
        }
    }

    /**
     * 快捷入口排序
     * */
    public function sortServiceQuick()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('service_quick')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 删除快捷入口
     * */
    public function delServiceQuick()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('service_quick')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('service_quick')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }


    /**
     * 评分列表
     * */
    public function scoreList()
    {
        $input = Request()->param();

        $type = $input['type'] ? : '';
        $user_id = $input['user_id'] ? : 0;

        if ($type) $where['l.type'] = $type;
        if ($user_id) $where['l.user_id'] = $user_id;

        $list = Db::name('user_score_log l')->join('user u', 'l.user_id = u.id', 'left')
            ->field('l.*,u.username,u.mobile')
            ->order('l.id desc')
            ->where($where)
            ->paginate()->each(function ($val) {
                if ($val['type'] == 'comment') $service_name = Db::name('order')->where(['id' => $val['link_id']])->value('service_name');
                $val['service_name'] = $service_name ? : '';

                return $val;
            });
        $this->assign('list', $list);

        $this->assign('title', '评分列表');

        return $this->view->fetch();
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $channel_user_id = $input['channel_user_id'];
        $service_name = $input['service_name'];
        $status = $input['status'];
        $date_range = $input['date_range'] ? : '';

        if (!empty($user_id)) $where["user_id"] = $user_id;
        if (!empty($channel_user_id)) $where["channel_user_id"] = $channel_user_id;
        if (!empty($service_name)) $where["service_name"] = ['LIKE', "%$service_name%"];
        if (!empty($status)) $where["status"] = $status;
        if ($date_range) {
            $date = explode(' - ', $date_range);
            $start_time = strtotime($date[0]);
            $end_time = strtotime($date[1]);

            $where["create_time"] = ['between', [$start_time, $end_time + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('order')->where($where)->order('id desc')->paginate()->each(function ($val) {
            $supplier_user_info = Db::name('user_ident')->where(['user_id' => $val['user_id'], 'type' => 1])->find();
            $val['supplier_username'] = $supplier_user_info['username'] ? : '';
            $val['supplier_mobile'] = $supplier_user_info['mobile'] ? : '';

            $channel_user_info = Db::name('user_ident')->where(['user_id' => $val['channel_user_id'], 'type' => 2])->find();
            $val['channel_username'] = $channel_user_info['username'] ? : '';
            $val['channel_mobile'] = $channel_user_info['mobile'] ? : '';

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', '订单列表');

        $supplier_user_list = Db::name('user_ident')->field('id,user_id,username,mobile')->where(['type' => 1, 'status' => 1])->select();
        $this->assign('supplier_user_list', $supplier_user_list);
        $channel_user_list = Db::name('user_ident')->field('id,user_id,username,mobile')->where(['type' => 2, 'status' => 1])->select();
        $this->assign('channel_user_list', $channel_user_list);

        return $this->fetch();
    }

    /**
     * 派单 / 重新派单
     * */
    public function editChannel()
    {
        $input = Request()->param();

        $id = $input['id'];
        $channel_user_id = $input['channel_user_id'];

        if (empty($id)) adminReturn(2, 'ID缺失');
        if (empty($channel_user_id)) adminReturn(2, '请选择渠道商');

        $order_info = Db::name('order')->where(['id' => $id])->find();
        if (empty($order_info)) adminReturn(2, '订单不存在或已删除');

        if ($order_info['status'] == 3) adminReturn(2, '该订单已完成，无法派单');

        if ($order_info['user_id'] == $channel_user_id) adminReturn(2, '供应商和渠道商是同一账号，无法派单');

        $data = [
            'update_time' => time(),
            'channel_user_id' => $channel_user_id,
            'status' => 2
        ];
        $res = Db::name('order')->where(['id' => $id])->update($data);
        if ($res) {
            adminReturn(1, '派单成功', url('orderList'));
        } else {
            adminReturn(2, '派单失败或未修改派单人');
        }
    }

    /**
     * 取消订单
     */
    public function cancelOrder()
    {
        $input = Request()->param();

        $id = $input["id"];

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('order')->where('id', $id)->find();
        if (empty($info)) adminReturn(2, '订单不存在或已删除');

        if ($info['status'] != 1) adminReturn(2, '订单状态异常，取消订单失败');

        $res = Db::name('order')->where(['id' => $id])->setField('status', -1);
        if ($res) {
            adminReturn(1, '删除公告成功', url('orderList'));
        } else {
            adminReturn(2, '删除公告失败');
        }
    }

    /**
     * 已完成订单
     */
    public function completeOrder()
    {
        $input = Request()->param();

        $id = $input['id'];
        $score = 2;

        if (empty($id)) adminReturn(2, '订单ID缺失');
        if (!in_array($score, [-1, 1, 2, 3])) adminReturn(2, '评分异常');

        $info = Db::name('order')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '订单不存在');

        $user_id = $info['user_id'];

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) adminReturn(2, '用户信息不存在');

        if ($channel_user_id = $info['channel_user_id']) {
            $channel_user_info = Db::name('user')->where(['id' => $channel_user_id])->find();
            if (empty($channel_user_info)) adminReturn(2, '渠道商信息不存在');
        }

        if ($service_id = $info['service_id']) {
            $service_info = Db::name('service')->where(['id' => $service_id])->find();
            if (empty($service_info)) adminReturn(2, '服务信息不存在');
        }

        Db::startTrans();
        try {
            $time = time();
            $data = [
                'score' => $score,
                'status' => 3,
                'comment_time' => $time
            ];

            // 修改订单数据
            $res = Db::name('order')->where(['id' => $id])->update($data);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '评分失败');
            }

            // 操作渠道商评分
            $remark = '完成一项服务，服务ID：' . $info['service_id'] . '；【' . $info['service_name'] . '】完成获得评分';
            $res = doScore($channel_user_id, $channel_user_info['channel_id'], 'channel_score', $score, 'comment', $info['id'], 'pu_order', $remark);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '评分失败');
            }

            $type_integral = Db::name('service_type')->where(['id' => $service_info['type_id']])->value('integral');
            if ($type_integral) {
                // 操作渠道商用户积分
                $res = doIntegral($channel_user_id, $type_integral, 'channel_complete', $id, 'pu_order', '渠道商完成服务交付');
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '评分失败');
                }
            }

            $comment_score_integral = C('COMMENT_SCORE_INTEGRAL');
            if ($comment_score_integral > 0 || $type_integral > 0) {
                // 操作供应商积分
                $supplier_remark = '';
                if ($comment_score_integral) $supplier_remark .= '主动评价+' . $comment_score_integral . '积分';
                if ($type_integral) $supplier_remark .= '，完成交易+' . $type_integral . '积分';
                $res = doIntegral($user_id, $comment_score_integral + $type_integral, 'supplier_comment_complete', $id, 'pu_order', $supplier_remark);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '评分失败');
                }
            }

            $salesman_share_integral = C('SALESMAN_SHARE_INTEGRAL');
            if ($user_info['supplier_first_order'] == 0 && $user_info['up_salesman_user_id'] > 0 && $salesman_share_integral > 0) {
                // 拉新完成首单，业务员奖励积分
                $res = doIntegral($user_info['up_salesman_user_id'], $salesman_share_integral, 'share_register', $id, 'pu_order', '拉新完成首单');
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '评分失败');
                }

                // 更新用户首单状态
                $res = Db::name('user')->where(['id' => $user_id])->setField('supplier_first_order', 1);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '评分失败');
                }
            }

            // 服务修改评分
            $res = Db::name('service')->where(['id' => $info['service_id']])->setField('score', $service_info['score'] + $score);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '评分失败');
            }

            // 真实服务人数+1
            $res = Db::name('service')->where(['id' => $info['service_id']])->setInc('count');
            if (!$res) {
                Db::rollback();
                adminReturn(2, '评分失败');
            }

            Db::commit();
            adminReturn(1, '评分成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '评分失败');
        }
    }

    /**
     * 订单详情
     */
    public function doOrder()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];

            $order_info = Db::name("order")->where(["id" => $id])->find();
            if ($order_info['status'] == 2) {
                $status = 3;
                $express_id = $input["express_id"];
                $send_num = $input["send_num"];
                if (empty($send_num)) adminReturn(2, "请输入快递编号");
                Db::startTrans();
                $data = [
                    "status" => $status,
                    "express_id" => $express_id,
                    "send_num" => $send_num,
                ];

                $data['update_time'] = time();
                $res = Db::name('order')->where(['id' => $id])->update($data);
                if ($res) {
                    /** 添加发送消息 */
                    $data_msg = [
                        "user_id" => $order_info["user_id"],
                        "order_id" => $id,
                        "title" => "您的订单已经发货",
                        "content" => "您的订单已经发货",
                        "type" => 1,
                        "create_time" => time(),
                    ];
                    Db::name("msg")->insert($data_msg);

                    /** 添加15天自动确认收货计划 */
                    $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                    $data_plan = [
                        "user_id" => $order_info["user_id"],
                        "order_id" => $id,
                        "type" => 2,
                        "execute_date" => date('Y - m - d', $time),
                    ];
                    Db::name("plan")->insert($data_plan);

                    Db::commit();
                    adminReturn(1, '编辑成功', url('orderList'));
                } else {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试');
                }
            } elseif ($order_info['status'] == 7) {
                $after_status = $input['after_status'];
                $after_refuse_reason = $input['after_refuse_reason'];
                if (empty($after_status)) adminReturn(2, '请选择售后操作');
                if ($after_status == 3 && empty($after_refuse_reason)) adminReturn(2, "请输入拒绝原因");

                $time = time();

                Db::startTrans();
                try {
                    $data = [
                        'back_order_sn' => $order_info['pay_order_sn'],
                        'status' => 8,//订单状态改成售后完成
                        'after_status' => $after_status,
                        'after_refuse_reason' => $after_refuse_reason,
                        'update_time' => $time
                    ];
                    Db::name('order')->where(['id' => $id])->update($data);

                    $price = $order_info['pay_price'];
                    /**
                     * @TODO 第5点暂时不做处理
                     * 同意售后【退货退款】（对应支付成功做退回处理）
                     * 1：金额原路退回（微信退款 || 收益退款）  注：如果是收益退款的话需要生成对应的收益记录，且用户可用收益增加
                     * 3：减少商品销量
                     * 4：增加商品库存
                     * 5：用户is_activation修改为已激活状态（1）【暂时不做处理】
                     * 6：冻结的直推、级差、服务津贴作废（作废）
                     * 7：删除自动确认收货任务
                     * 同意售后【换货】
                     * 1：订单变成待收货状态
                     * 2：删除原来的自动确认收货任务
                     * 3：新增自动确认收货任务
                     * */
                    if ($after_status == 2) {
                        // 同意售后

                        if ($input['after_type'] == '退货退款') {
                            $vice_order_info = Db::name('vice_order')->where(['order_id' => $id])->find();

                            // 1：金额原路退回
                            if ($order_info['pay_type'] == 1) {
                                //微信支付
                                Loader::import('wxpaysdk\wxPay', EXTEND_PATH);
                                $obj = new \wxPay();

                                $obj->refund($price, $price, $order_info['pay_order_sn'], $order_info['pay_order_sn'], $order_info['after_reason']);
                            } else {
                                $user_id = $order_info['user_id'];

                                $user_info = Db::name('user')->where(['id' => $user_id])->find();
                                $mobile = $user_info['mobile'] ? : '';
                                $gzh_openid = $user_info['gzh_openid'];

                                Db::name('user')->where(['id' => $user_id])->setInc('all_profit', $price);

                                //收益支付
                                $profit_data = [
                                    'order_id' => $id,
                                    'user_id' => $order_info['user_id'],
                                    'price' => $order_info['pay_price'],
                                    'type' => 12,
                                    'status' => 2,
                                    'create_time' => $time
                                ];
                                Db::name('profit')->insert($profit_data);

                                // 发送微信公众号模板消息
                                $template_msg = [
                                    'first' => [
                                        'value' => '您好，您的售后订单购物抵扣收益已退回',
                                        'color' => '#743A3A'
                                    ],
                                    'keyword1' => [
                                        'value' => '购物抵扣收益退款',
                                        'color' => '#743A3A'
                                    ],
                                    'keyword2' => [
                                        'value' => $price,
                                        'color' => '#743A3A'
                                    ],
                                    'keyword3' => [
                                        'value' => date('Y-m-d'),
                                        'color' => '#743A3A'
                                    ],
                                    'keyword4' => [
                                        'value' => '点击查看',
                                        'color' => '#743A3A'
                                    ],
                                    'remark' => [
                                        'value' => '',
                                        'color' => '#743A3A'
                                    ]
                                ];
                                $page = 'pages/my_income/my_income?user_id=' . $user_id . '&mobile=' . $mobile;
                                if ($gzh_openid && $price > 0) sendWxTemplateNotice($gzh_openid, $template_msg, 12, $page);
                            }

                            $buy_count = $vice_order_info['count'];
                            $goods_id = $vice_order_info['goods_id'];
                            $sku_id = $vice_order_info['sku_id'];

                            // 3：减少商品销量
                            $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                            if ($goods_info && $buy_count > 0) Db::name('goods')->where(['id' => $goods_id])->setDec('sales_count', $buy_count);

                            // 4：增加商品库存
                            $sku_info = Db::name('sku_value')->where(['goods_id' => $goods_id, 'sku_id' => $sku_id])->find();
                            if ($sku_info && $buy_count > 0) Db::name('sku_value')->where(['goods_id' => $goods_id, 'sku_id' => $sku_id])->setInc('stock', $buy_count);

                            // 6：冻结的直推、级差、服务津贴作废（作废）
                            $frozen_profit_list = Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->select();
                            if ($frozen_profit_list) {
                                $update_profit_data = ['status' => -1,
                                                       'update_time' => $time];
                                Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->update($update_profit_data);
                            }

                            // 7：删除自动确认收货任务
                            Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();
                        } else
                            if ($input['after_type'] == '换货') {
                                // 1：订单变成待收货状态
                                $change_order_data = [
                                    'status' => 3,
                                    'update_time' => $time
                                ];
                                Db::name('order')->where(['id' => $id])->update($change_order_data);
                                // 2：删除原来的自动确认收货任务
                                Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();
                                // 3：新增自动确认收货任务
                                $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                                $data_plan = [
                                    "user_id" => $order_info["user_id"],
                                    "order_id" => $id,
                                    "type" => 2,
                                    "execute_date" => date('Y-m-d', $time),
                                ];
                                Db::name("plan")->insert($data_plan);
                            }
                    }

                    Db::commit();
                    adminReturn(1, '操作成功', url('orderList'));
                } catch
                (\Exception $e) {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试~');
                }
            }
        } else {
            $id = input("id");
            $order_info = Db::name('order a')->field("a.*,b.mobile,b.username")->where(["a.id" => $id])->join('user b', "a.user_id = b.id", "left")->find();
            $order_vice = Db::name("vice_order")->where(["order_id" => $id])->select();
            foreach ($order_vice as &$vo) {
                $suk_value_arr = explode("-", $vo['sku_id']);
                $suk_name_str = "";
                foreach ($suk_value_arr as $vv) {
                    $sku_info = Db::name("sku")->where(["id" => $vv])->find();
                    $sku_p_info = Db::name("sku")->where(["id" => $sku_info['pid']])->find();
                    $suk_name_str .= $sku_p_info['name'] . ": " . $sku_info['name'] . ";";
                }
                $vo['suk_name_str'] = $suk_name_str;
                $gift_ids_arr = explode("-", $vo['gift_ids']);

                /** 查看商品是不是有评论 */
                $is_have = Db::name('goods_comment')->where(["order_id" => $id, "goods_id" => $vv['goods_id']])->value("id");
                if ($is_have) {
                    $is_comment = $is_have;
                } else {
                    $is_comment = 0;
                }
                $vo['is_comment'] = $is_comment;
            }

            //查询出快递公司
            $express_list = Db::name("express")->field("id,name")->select();

            if ($express_id = $order_info['express_id']) $order_info['express_name'] = Db::name('express')->where(['id' => $express_id])->value('name');

            $this->assign('info', $order_info);
            $this->assign('order_vice', $order_vice);
            $this->assign('express_list', $express_list);

            $this->assign('title', '订单详情');
            return $this->fetch();
        }
    }

    /**
     *商品评论
     */
    public function doComment()
    {
        $input = Request()->param();
        $id = $input["id"];

        //查询出评论内容
        $info = Db::name('goods_comment')->where(["id" => $id])->find();

        $info["img_arr"] = explode(",", $info["imgs"]);

        $this->assign('info', $info);
        $this->assign('title', '评论详情');
        return $this->fetch();
    }

    /**
     * 公告列表
     */
    public function msgList()
    {
        $input = Request()->param();

        $title = $input['title'];
        $where["type"] = 3;
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 公告
     */
    public function doMsg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $title = $input["title"];
            $content = $input["content"];

            if (empty($title)) adminReturn(2, "请输入标题");
            if (empty($content)) adminReturn(2, "请填写公告内容");

            if ($id) {
                $data = [
                    'title' => $title,
                    'content' => $content
                ];

                $res = Db::name('msg')->where(['id' => $id])->update($data);
            } else {
                $data = [
                    "user_id" => 0,
                    "title" => $title,
                    "content" => $content,
                    "type" => 3,
                    "look_count" => 0,
                    "create_time" => time()
                ];

                $res = Db::name('msg')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '公告成功', url('msgList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '公告失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('msg')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '公告详情' : '新增公告'));

            return $this->view->fetch();
        }
    }

    /**
     * 删除公告
     */
    public function delMsg()
    {
        $input = Request()->param();

        $id = $input["id"];

        if ($id > 0) {
            $res = Db::name('msg')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除公告成功', url('msgList'));
            } else {
                adminReturn(2, '删除公告失败');
            }
        }
    }

    /**
     * 招标计划
     */
    public function bidPlanList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 2;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '招标计划');

        return $this->fetch();
    }

    /**
     * 招标计划详情
     * */
    public function bidPlanDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '招标计划详情');

        return $this->view->fetch();
    }

    /**
     * 住建工程
     */
    public function constructionList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 3;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '住建工程');

        return $this->fetch();
    }

    /**
     * 住建工程详情
     * */
    public function constructionDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '住建工程详情');

        return $this->view->fetch();
    }

    /**
     * 交通工程
     */
    public function transporatationList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 4;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '交通工程');

        return $this->fetch();
    }

    /**
     * 交通工程详情
     * */
    public function transporatationDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '交通工程详情');

        return $this->view->fetch();
    }

    /**
     * 水利工程
     */
    public function waterConservancyList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 5;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '水利工程');

        return $this->fetch();
    }

    /**
     * 水利工程详情
     * */
    public function waterConservancyDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '水利工程详情');

        return $this->view->fetch();
    }

    /**
     * 工业工程
     */
    public function industryList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 6;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '工业工程');

        return $this->fetch();
    }

    /**
     * 工业工程详情
     * */
    public function industryDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '工业工程详情');

        return $this->view->fetch();
    }

    /**
     * 代建工程
     */
    public function agencyConstructionList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 7;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '代建工程');

        return $this->fetch();
    }

    /**
     * 代建工程详情
     * */
    public function agencyConstructionDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '代建工程详情');

        return $this->view->fetch();
    }

    /**
     * 农业项目
     */
    public function agriculturalProjectList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 8;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '农业项目');

        return $this->fetch();
    }

    /**
     * 农业项目详情
     * */
    public function agriculturalProjectDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '农业项目详情');

        return $this->view->fetch();
    }

    /**
     * 环保项目
     */
    public function environmentalProjectList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 9;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '环保项目');

        return $this->fetch();
    }

    /**
     * 环保项目详情
     * */
    public function environmentalProjectDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '环保项目详情');

        return $this->view->fetch();
    }

    /**
     * 其他
     */
    public function otherList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['two_type_id'] = 11;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '其他');

        return $this->fetch();
    }

    /**
     * 其他详情
     * */
    public function otherDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '其他详情');

        return $this->view->fetch();
    }

    /**
     * 政府采购
     */
    public function purchaseList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['one_type_id'] = 12;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '政府采购');

        return $this->fetch();
    }

    /**
     * 政府采购详情
     * */
    public function purchaseDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $info['content_json'] = json_decode($info['content_json'], true);

        $this->assign('info', $info);
        $this->assign('title', '政府采购详情');

        return $this->view->fetch();
    }

    /**
     * 土地使用权
     */
    public function tdList()
    {
        $input = Request()->param();

        $search_value = $input['title'] ? : '';

        $where['two_type_id'] = 15;
        if ($search_value) $where['landName|resourceName'] = ['like', "%{$search_value}%"];

        $list = Db::name('gather_resource')->where($where)->order('publish_time desc')->paginate()->each(function ($v) {
            $v['quote_num'] = '';
            if ($v['highestQuote']) {
                $highestQuote = json_decode($v['highestQuote'], true);
                $v['quote_num'] = number_format($highestQuote['quote_num']) . '万元';
            }

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '土地使用权');

        return $this->fetch();
    }

    /**
     * 集体建设用地
     */
    public function ydList()
    {
        $input = Request()->param();

        $search_value = $input['title'] ? : '';

        $where['two_type_id'] = 16;
        if ($search_value) $where['landName|resourceName'] = ['like', "%{$search_value}%"];

        $list = Db::name('gather_resource')->where($where)->order('publish_time desc')->paginate()->each(function ($v) {
            $v['quote_num'] = '';
            if ($v['highestQuote']) {
                $highestQuote = json_decode($v['highestQuote'], true);
                $v['quote_num'] = number_format($highestQuote['quote_num']) . '万元';
            }

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '集体建设用地');

        return $this->fetch();
    }

    /**
     * 增减挂钩结余指标
     */
    public function zbList()
    {
        $input = Request()->param();

        $search_value = $input['title'] ? : '';

        $where['two_type_id'] = 17;
        if ($search_value) $where['landName'] = ['like', "%{$search_value}%"];

        $list = Db::name('gather_resource')->where($where)->order('publish_time desc')->paginate()->each(function ($v) {
            $v['quote_num'] = '';
            if ($v['highestQuote']) {
                $highestQuote = json_decode($v['highestQuote'], true);
                $v['quote_num'] = number_format($highestQuote['quote_num']) . '万元';
            }

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '增减挂钩结余指标');

        return $this->fetch();
    }

    /**
     * 补充耕地指标
     */
    public function bcList()
    {
        $input = Request()->param();

        $search_value = $input['title'] ? : '';

        $where['two_type_id'] = 18;
        if ($search_value) $where['landName'] = ['like', "%{$search_value}%"];

        $list = Db::name('gather_resource')->where($where)->order('publish_time desc')->paginate()->each(function ($v) {
            $v['quote_num'] = '';
            if ($v['highestQuote']) {
                $highestQuote = json_decode($v['highestQuote'], true);
                $v['quote_num'] = number_format($highestQuote['quote_num']) . '万元';
            }

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '补充耕地指标');

        return $this->fetch();
    }

    /**
     * 矿业权
     */
    public function kyqList()
    {
        $input = Request()->param();

        $search_value = $input['title'] ? : '';

        $where['two_type_id'] = ['IN', [19, 28]];
        if ($search_value) $where['landName|resourceName'] = ['like', "%{$search_value}%"];

        $list = Db::name('gather_resource')->where($where)->order('publish_time desc')->paginate()->each(function ($v) {
            /*$render_data = [
                ['label' => '挂牌时间', 'value' => $v['listStartTime'] . ' 至 ' . $v['listEndTime']],
                ['label' => '探矿权名称', 'value' => $v['resourceName']],
                ['label' => '保证金到账截止时间', 'value' => $v['depositEndTime']],
                ['label' => '保证金', 'value' => number_format($v['amountReceived']) . '万元'],
                ['label' => '资源位置', 'value' => $v['landLocation']],
                ['label' => '起始价', 'value' => number_format($v['initQuote']) . '万元']
            ];*/

            $v['quote_num'] = '';
            if ($v['highestQuote']) {
                $highestQuote = json_decode($v['highestQuote'], true);
                $v['quote_num'] = number_format($highestQuote['quote_num']) . '万元';
            }

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '矿业权');

        return $this->fetch();
    }

    /**
     * 林权
     */
    public function lqList()
    {
        $input = Request()->param();

        $search_value = $input['title'] ? : '';

        $where['two_type_id'] = 21;
        if ($search_value) $where['landName'] = ['like', "%{$search_value}%"];

        $list = Db::name('gather_resource')->where($where)->order('publish_time desc')->paginate()->each(function ($v) {
            $v['quote_num'] = '';
            if ($v['highestQuote']) {
                $highestQuote = json_decode($v['highestQuote'], true);
                $v['quote_num'] = number_format($highestQuote['quote_num']) . '万元';
            }

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '林权');

        return $this->fetch();
    }

    /**
     * 国有资产
     */
    public function gyzcList()
    {
        $input = Request()->param();

        $search_value = $input['title'] ? : '';

        if ($search_value) {
            $where['markName'] = ['LIKE', "%$search_value%"];
        } else {
            $where['markName'] = ['NOT NULL', ''];
        }

        $list = Db::name('gather_property')->field('id,markName,processNo,depositNeedPay,initQuote,applyStartTime,applyEndTime')->where($where)->order('id desc')->paginate()->each(function ($v) {
            $v['depositNeedPay'] = number_format($v['depositNeedPay']) . '万元';
            $v['initQuote'] = number_format($v['initQuote']) . '万元';
            $v['applyStartTime'] = date('Y-m-d H:i', strtotime($v['applyStartTime']));
            $v['applyEndTime'] = date('Y-m-d H:i', strtotime($v['applyEndTime']));

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '国有资产');

        return $this->fetch();
    }

    /**
     * 环境权
     */
    public function hjList()
    {
        $input = Request()->param();

        $search_value = $input['title'] ? : '';

        $where['one_type_id'] = 23;

        if ($search_value) $where['processNo'] = ['LIKE', "%$search_value%"];

        $list = Db::name('gather_environment')->where($where)->order('id desc')->paginate()->each(function ($v) {
            $v['listStartTime'] = $v['listStartTime'] ? date('Y-m-d H:i', strtotime($v['listStartTime'])) : '';
            $v['listEndTime'] = $v['listEndTime'] ? date('Y-m-d H:i', strtotime($v['listEndTime'])) : '';

            $v['quoteUnit'] = $v['quoteUnitName'] ? : doQuoteUnit($v['quoteUnit']);

            $v['initQuote'] = $v['initQuote'] ? number_format($v['initQuote']) : 0;
            $v['quoteRange'] = $v['quoteRange'] ? number_format($v['quoteRange']) : 0;

            $topQuoteNum = json_encode($v['topQuoteNum'], JSON_UNESCAPED_UNICODE);
            if ($topQuoteNum) {
                $high = number_format($topQuoteNum['quote_num']) . doQuoteUnit($topQuoteNum['quote_unit']);
            } else {
                $high = '暂无最新出价';
            }
            $v['high'] = $high;

            // 交易方式
            switch ($v['processType']) {
                case 'INCREMENTAL_BIDDING':
                case 'REVERSE_BIDDING':
                    $processTypeDesc = '公开竞价';
                    break;
                case 'GOVERNMENT_REPURCHASE':
                    $processTypeDesc = '政府回购';
                    break;
                case 'AGREEMENT_TRANSFER':
                    $processTypeDesc = '协议转让';
                    break;
            }
            $v['processTypeDesc'] = $processTypeDesc ? : '';

            // 交易类型
            $v['processCategoryDesc'] = $v['processCategory'] == 'TRANSFER' ? '转让' : '受让';

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '环境权');

        return $this->fetch();
    }


    /**
     * 其他交易
     */
    public function qtjyList()
    {
        $input = Request()->param();

        $title = $input['title'] ? : '';

        $where['one_type_id'] = 27;
        if ($title) $where['title'] = ['LIKE', "%$title%"];

        $list = Db::name('gather')->where($where)->order('publish_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '其他交易');

        return $this->fetch();
    }


    /**
     * 其他交易详情
     * */
    public function qtjyDetail()
    {
        $id = Request()->param('id');

        $info = Db::name('gather')->where(['id' => $id])->find();

        $this->assign('info', $info);
        $this->assign('title', '其他交易详情');

        return $this->view->fetch();
    }

}
